// API工具函数
const app = getApp();

// 基础请求函数
const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync("token");

    wx.request({
      url: `${app.globalData.baseUrl}${options.url}`,
      method: options.method || "GET",
      data: options.data || {},
      header: {
        "Content-Type": "application/json",
        Authorization: token ? `Bearer ${token}` : "",
        ...options.header,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(new Error(res.data.message || "请求失败"));
        }
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};

// GET请求
const get = (url, data = {}) => {
  return request({
    url,
    method: "GET",
    data,
  });
};

// POST请求
const post = (url, data = {}) => {
  return request({
    url,
    method: "POST",
    data,
  });
};

// PUT请求
const put = (url, data = {}) => {
  return request({
    url,
    method: "PUT",
    data,
  });
};

// DELETE请求
const del = (url, data = {}) => {
  return request({
    url,
    method: "DELETE",
    data,
  });
};

// 文件上传
const uploadFile = (url, filePath, name = "file", formData = {}) => {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync("token");

    wx.uploadFile({
      url: `${app.globalData.baseUrl}${url}`,
      filePath,
      name,
      formData,
      header: {
        Authorization: token ? `Bearer ${token}` : "",
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (res.statusCode === 200) {
          resolve(data);
        } else {
          reject(new Error(data.message || "上传失败"));
        }
      },
      fail: reject,
    });
  });
};

// 认证相关API
const auth = {
  // 登录
  login: (data) => {
    return post("/auth/login", data);
  },

  // 验证token
  validate: () => {
    return post("/auth/validate");
  },

  // 登出
  logout: () => {
    return post("/auth/logout");
  },
};

// 学生端API
const student = {
  // 个人信息
  getProfile: () => {
    return get("/student/profile");
  },

  updateProfile: (data) => {
    return post("/student/profile/update", data);
  },

  // 成绩单
  getTranscriptList: () => {
    return get("/student/transcript/list");
  },

  saveTranscript: (data) => {
    return post("/student/transcript/save", data);
  },

  // 科研成果
  getResearchList: () => {
    return get("/student/research/list");
  },

  addResearch: (data) => {
    return post("/student/research/add", data);
  },

  updateResearch: (id, data) => {
    return put(`/student/research/${id}`, data);
  },

  deleteResearch: (id) => {
    return del(`/student/research/${id}`);
  },

  // 申请状态
  getApplicationStatus: () => {
    return get("/student/application/status");
  },

  submitApplication: () => {
    return post("/student/application/submit");
  },

  getApplicationInfo: () => {
    return get("/student/application/info");
  },

  getMaterialsStatus: () => {
    return get("/student/application/materials/status");
  },
};

// 评委端API
const judge = {
  // 统计数据
  getStats: () => {
    return get("/judge/stats");
  },

  // 申请列表
  getApplications: (filter = "all") => {
    return get("/judge/applications", { filter });
  },

  // 申请详情
  getApplicationDetail: (id) => {
    return get("/judge/application/detail", { id });
  },

  // 评审
  submitReview: (data) => {
    return post("/judge/review/submit", data);
  },

  saveReviewDraft: (data) => {
    return post("/judge/review/draft", data);
  },

  // 评分
  getScores: (filters = {}) => {
    return get("/judge/scores", filters);
  },

  deleteScore: (id) => {
    return del("/judge/scores/delete", { id });
  },
};

// 文件上传API
const upload = {
  // 上传图片（云函数版本）
  uploadImage: (filePath) => {
    return new Promise((resolve, reject) => {
      // 先读取文件为base64
      wx.getFileSystemManager().readFile({
        filePath: filePath,
        encoding: "base64",
        success: (fileRes) => {
          // 调用云函数上传
          wx.cloud.callFunction({
            name: "upload-image",
            data: {
              fileContent: fileRes.data,
              fileName: filePath.split("/").pop() || "image.jpg",
            },
            success: (res) => {
              if (res.result && res.result.code === 0) {
                resolve(res.result.data);
              } else {
                reject(new Error(res.result?.message || "上传失败"));
              }
            },
            fail: (error) => {
              reject(error);
            },
          });
        },
        fail: (error) => {
          reject(error);
        },
      });
    });
  },

  // 上传文件（云函数版本）
  uploadFile: (filePath, name = "file") => {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath: filePath,
        encoding: "base64",
        success: (fileRes) => {
          wx.cloud.callFunction({
            name: "upload-image",
            data: {
              fileContent: fileRes.data,
              fileName: name,
            },
            success: (res) => {
              if (res.result && res.result.code === 0) {
                resolve(res.result.data);
              } else {
                reject(new Error(res.result?.message || "上传失败"));
              }
            },
            fail: (error) => {
              reject(error);
            },
          });
        },
        fail: (error) => {
          reject(error);
        },
      });
    });
  },
};

// OCR识别API
const ocr = {
  // 识别成绩单（云函数版本）
  recognizeTranscript: (imageUrl) => {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: "ocr-recognize",
        data: { imageUrl },
        success: (res) => {
          console.log("OCR云函数响应:", res);
          if (res.result && res.result.code === 0) {
            resolve(res.result);
          } else {
            reject(new Error(res.result?.message || "识别失败"));
          }
        },
        fail: (error) => {
          console.error("OCR云函数调用失败:", error);
          reject(error);
        },
      });
    });
  },

  // 识别身份证（云函数版本）
  recognizeIdCard: (imageUrl) => {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: "ocr-recognize",
        data: { imageUrl },
        success: (res) => {
          console.log("OCR云函数响应:", res);
          if (res.result && res.result.code === 0) {
            resolve(res.result);
          } else {
            reject(new Error(res.result?.message || "识别失败"));
          }
        },
        fail: (error) => {
          console.error("OCR云函数调用失败:", error);
          reject(error);
        },
      });
    });
  },
};

// 错误处理
const handleError = (error) => {
  console.error("API Error:", error);

  if (error.message.includes("token")) {
    // token过期，跳转到登录页
    wx.removeStorageSync("token");
    wx.removeStorageSync("userInfo");
    wx.removeStorageSync("userType");
    wx.reLaunch({
      url: "/pages/login/login",
    });
    return;
  }

  wx.showToast({
    title: error.message || "网络错误",
    icon: "error",
  });
};

// 带错误处理的请求
const safeRequest = async (requestFn) => {
  try {
    const result = await requestFn();
    return { success: true, data: result };
  } catch (error) {
    handleError(error);
    return { success: false, error: error.message };
  }
};

module.exports = {
  request,
  get,
  post,
  put,
  del,
  uploadFile,
  auth,
  student,
  judge,
  upload,
  ocr,
  handleError,
  safeRequest,
};
